package com.camunda.workflow.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.filter.SimplePropertyPreFilter;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ObjUtil {
    /**
     * 判断对象是否为空。支持 String、Collection、Map、Iterable、Array、Object。
     */
    public static boolean isNull(Object obj, String... ignoreFields) {
        if (obj instanceof CharSequence) {
            CharSequence charSequence = (CharSequence) obj;
            return !StringUtils.hasText(charSequence) || "".contentEquals(charSequence);
        } else if (obj instanceof Iterable) {// Collection
            Iterator<?> iterator = ((Iterable<?>) obj).iterator();
            return !iterator.hasNext();
        } else if (obj instanceof Map) {
            Map<?, ?> map = (Map<?, ?>) obj;
            return map.isEmpty();
        } else {
            try {
                SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
                Set<String> excludes = filter.getExcludes();
                excludes.addAll(Stream.of("intervals", "sorts", "pageNum", "pageSize").collect(Collectors.toList()));
                excludes.addAll(Arrays.asList(ignoreFields));
                String objStr = JSON.toJSONString(obj, filter);
                return objStr == null || "{}".equals(objStr) || "[]".equals(objStr) || "null".equals(objStr);
            } catch (Exception e) {
                return Objects.isNull(obj);
            }
        }
    }

    /**
     * 判断对象不为空
     */
    public static boolean isNotNull(Object obj, String... ignoreFields) {
        return !isNull(obj, ignoreFields);
    }

//    public static void main(String[] args) {
//        SysRole sysRole = new SysRole();
//        sysRole.setId(12L);
////        sysRole.setName("12");
//        System.out.println(sysRole);
//        boolean b = isNull(null);
//        System.out.println(b);
//    }
}
